package com.tan00xu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tan00xu.dao.*;
import com.tan00xu.dao.dos.Archives;
import com.tan00xu.pojo.*;
import com.tan00xu.service.*;
import com.tan00xu.utils.UserThreadLocal;
import com.tan00xu.vo.*;
import com.tan00xu.vo.params.ArticleParam;
import com.tan00xu.vo.params.PageParams;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private TagService tagService;

    @Autowired
    private UserService userService;

    @Autowired
    private ArticleTagMapper articleTagMapper;


    @Autowired
    private ArticleBodyMapper articleBodyMapper;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private CommentMapper commentMapper;

    @Override
    public Result listArchivesByPageParams(PageParams pageParams) {
        /**
         * 分页查询article表
         */
        Page<Article> page = new Page<>(pageParams.getPage(), pageParams.getSize());
        IPage<Article> articleIPage = articleMapper.listArchivesByPageParams(
                page,
                pageParams.getCategoryId(),
                pageParams.getTagId(),
                pageParams.getYear(),
                pageParams.getMonth()
        );
        List<Article> records = articleIPage.getRecords();
        return Result.success("获取文章列表成功", copyList(records, true, true));
    }

    @Override
    public Result listArticles(PageParams pageParams) {
        /**
         * 分页查询article表
         */
        Page<Article> page = new Page<>(pageParams.getPage(), pageParams.getSize());
//        LambdaQueryWrapper
//        QueryWrapper
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();

        //如果前端传回的值中存在CategoryId，就加入查询条件
        if (pageParams.getCategoryId() != null) {
            queryWrapper.eq(Article::getCategoryId, pageParams.getCategoryId());
        }
        //如果前端传回的值中存在getTagId，就加入查询条件
        List<Long> articleList = new ArrayList<>();
        if (pageParams.getTagId() != null) {
            //查出该tag下的所有文章
            LambdaQueryWrapper<ArticleTag> articleTagQueryWrapper = new LambdaQueryWrapper<>();
            articleTagQueryWrapper.eq(ArticleTag::getTagId, pageParams.getTagId());
            //获取到该tag下的所有文章id
            articleTagQueryWrapper.select(ArticleTag::getArticleId);
            //得到该tag下的所有对应信息
            List<ArticleTag> articleTags = articleTagMapper.selectList(articleTagQueryWrapper);
            //将所有文章id放入articleList
            articleTags.forEach(articleTag -> {
                articleList.add(articleTag.getArticleId());
            });
            if (articleTags.size() > 0) {
                //and id in ()
                queryWrapper.in(Article::getId, articleList);
            } else {
                queryWrapper.eq(Article::getId, -1);
            }
        }

        //查询条件,是否置顶排序,按时间倒序
        queryWrapper.orderByDesc(Article::getWeight, Article::getCreateDate);
        Page<Article> articlePage = articleMapper.selectPage(page, queryWrapper);
        List<Article> records = articlePage.getRecords();

        List<ArticleVo> articleVoList = copyList(records, true, true);

        return Result.success(articleVoList);
    }

    /**
     * 最热文章列表
     *
     * @param limit
     * @return
     */
    @Override
    public Result listHotArticles(int limit) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        /*
            select id, title
            from blog_article
            order by view_counts desc
            limit 5;
         */
        queryWrapper.orderByDesc(Article::getViewCounts);
        queryWrapper.select(Article::getId, Article::getTitle, Article::getCreateDate);
        queryWrapper.last("limit " + limit);
        List<Article> articles = articleMapper.selectList(queryWrapper);
        return Result.success(copyList(articles, false, false));
    }

    /**
     * 获取最新文章
     *
     * @param limit 条数
     * @return
     */
    @Override
    public Result listNewArticles(int limit) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();

        /*
            select id, title
            from blog_article
            order by create_date desc
            limit 5;
         */
        queryWrapper.orderByDesc(Article::getCreateDate);
        queryWrapper.select(Article::getId, Article::getTitle, Article::getCreateDate);
        queryWrapper.last("limit " + limit);
        List<Article> articles = articleMapper.selectList(queryWrapper);
        return Result.success(copyList(articles, false, false));
    }

    /**
     * 获取文章归档
     *
     * @return
     */
    @Override
    public Result listArchives() {
        List<Archives> archivesList = articleMapper.listArchives();
        return Result.success(archivesList);
    }

    @Autowired
    private ThreadService threadService;

    /**
     * 根据文章id获取文章详情
     *
     * @param articleId 文章id
     * @return Result
     */
    @Override
    public Result getArticleById(Long articleId) {
        /*
            1. 根据文章id查询文章详情
            2. 根据文章id和分类id查询文章分类
            3.
         */
        Article article = this.articleMapper.selectById(articleId);
        ArticleVo articleVo = copy(article, true, true, true, true);
        threadService.updateArticelViewConts(articleMapper, article);
        return Result.success(articleVo);
    }

    /**
     * 新增文章
     *
     * @param articleParam 文章参数
     * @return Result
     */
    @Override
    public Result publishArticle(ArticleParam articleParam) {
        /**
         * 获取当前登录用户
         * 此接口必须加入到登录拦截器中
         */
        User user = UserThreadLocal.get();

        Article article = new Article();
        boolean isEdit = false;
        if (articleParam.getId() != null) {
            article.setId(articleParam.getId());
            article.setTitle(articleParam.getTitle());
            article.setSummary(articleParam.getSummary());
            article.setCategoryId(articleParam.getCategory().getId());
            articleMapper.updateById(article);
            isEdit = true;
        } else {
            article.setAuthorId(user.getId());
            article.setWeight(Article.Article_TOP);
            article.setViewCounts(0);
            article.setCommentCounts(0);
            article.setTitle(articleParam.getTitle());
            article.setSummary(articleParam.getSummary());
            article.setCreateDate(System.currentTimeMillis());
            article.setCategoryId(articleParam.getCategory().getId());
            articleMapper.insert(article);
        }

        //获取到标签
        List<TagVo> tags = articleParam.getTags();
        //设置文章标签 文章和标签的关联表
        if (tags != null && tags.size() > 0) {
            Long articleId = article.getId();
            //如果是编辑，就先删除原有的标签信息
            if (isEdit) {
                LambdaQueryWrapper<ArticleTag> queryWrapper = Wrappers.lambdaQuery();
                queryWrapper.eq(ArticleTag::getArticleId, articleId);
                articleTagMapper.delete(queryWrapper);
            }
            for (TagVo tag : tags) {
                ArticleTag articleTag = new ArticleTag();
                articleTag.setArticleId(articleId);
                articleTag.setTagId(tag.getId());
                articleTagMapper.insert(articleTag);
            }
        }
        //设置文章内容 文章内容表
        if (isEdit) {
            ArticleBody articleBody = new ArticleBody();
            articleBody.setArticleId(article.getId());
            articleBody.setContentMarkdown(articleParam.getBody().getContentMarkdown());
            articleBody.setContentHtml(articleParam.getBody().getContentHtml());
            LambdaUpdateWrapper<ArticleBody> updateWrapper = Wrappers.lambdaUpdate();
            updateWrapper.eq(ArticleBody::getArticleId, article.getId());
            articleBodyMapper.update(articleBody, updateWrapper);
        } else {
            ArticleBody articleBody = new ArticleBody();
            articleBody.setArticleId(article.getId());
            articleBody.setContentMarkdown(articleParam.getBody().getContentMarkdown());
            articleBody.setContentHtml(articleParam.getBody().getContentHtml());
            articleBodyMapper.insert(articleBody);
            //设置文章表的，文章内容id
            article.setBodyId(articleBody.getId());
            articleMapper.updateById(article);
        }

        Map<String, String> data = new HashMap<>();
        data.put("articleId", article.getId().toString());
        if (isEdit) {
            return Result.success("编辑成功", data);
        }
        return Result.success("发布成功啦", data);
    }

    /**
     * 根据文章id删除文章
     *
     * @param articleId 文章id
     * @param token     用户token
     * @return
     */
    @Override
    public Result deleteArticleByArticleId(Long articleId, String token) {
        //敏感操作，需要验证token
        User user = tokenService.checkToken(token);
        Article article = articleMapper.selectById(articleId);
        if (user != null && article != null && article.getAuthorId().equals(user.getId())) {
            //删除文章
            articleMapper.deleteById(articleId);
            //删除文章内容
            LambdaQueryWrapper<ArticleBody> articleBodyQueryWrapper = Wrappers.lambdaQuery();
            articleBodyQueryWrapper.eq(ArticleBody::getArticleId, articleId);
            articleBodyMapper.delete(articleBodyQueryWrapper);
            //删除文章对应的标签
            LambdaQueryWrapper<ArticleTag> articleTagQueryWrapper = Wrappers.lambdaQuery();
            articleTagQueryWrapper.eq(ArticleTag::getArticleId, articleId);
            articleTagMapper.delete(articleTagQueryWrapper);
            //删除文章对应的评论
            LambdaQueryWrapper<Comment> commentQueryWrapper = Wrappers.lambdaQuery();
            commentQueryWrapper.eq(Comment::getArticleId, articleId);
            commentMapper.delete(commentQueryWrapper);

            return Result.success("文章删除成功");
        }
        return Result.fail(90002,"文章删除失败");
    }


    private List<ArticleVo> copyList(List<Article> records, Boolean isTag, Boolean isAuthor, boolean isBody, boolean isCategory) {

        List<ArticleVo> articleVoList = new ArrayList<>();
        for (Article article : records) {
            ArticleVo articleVo = copy(article, isTag, isAuthor, isBody, isCategory);
            articleVoList.add(articleVo);
        }
        return articleVoList;

    }

    /**
     * 拷贝list
     */
    private List<ArticleVo> copyList(List<Article> records, Boolean isTag, Boolean isAuthor) {

        List<ArticleVo> articleVoList = new ArrayList<>();
        for (Article article : records) {
            ArticleVo articleVo = copy(article, isTag, isAuthor, false, false);
            articleVoList.add(articleVo);
        }
        return articleVoList;

    }

    private ArticleVo copy(Article article, Boolean isTag, Boolean isAuthor, boolean isBody, boolean isCategory) {
        ArticleVo articleVo = new ArticleVo();
        BeanUtils.copyProperties(article, articleVo);

        articleVo.setCreateDate(new DateTime(article.getCreateDate()).toString("yyyy-MM-dd HH:mm:ss"));

        //是否需要携带标签
        if (isTag) {
            Long articleId = article.getId();

            articleVo.setTags(tagService.getTageByArticleId(articleId));
        }
        if (isAuthor) {
            Long authorId = article.getAuthorId();
            //获取到作者信息
            UserVo userVoByUserId = userService.getUserVoByUserId(authorId);

            articleVo.setAuthor(userVoByUserId);
//            articleVo.setAuthor(userService.getUserById(authorId).getNickname());
        }
        if (isBody) {
            Long bodyId = article.getBodyId();
            articleVo.setBody(getArticleBodyByBodyId(bodyId));
        }
        if (isCategory) {
            //获取分类id
            Long categoryId = article.getCategoryId();
            articleVo.setCategory(categoryService.getCategoryById(categoryId));
        }

        return articleVo;
    }


    /**
     * 根据文章内容id获取文章内容
     *
     * @param bodyId 文章内容id
     * @return
     */
    private ArticleBodyVo getArticleBodyByBodyId(Long bodyId) {
        ArticleBody articleBody = articleBodyMapper.selectById(bodyId);
        ArticleBodyVo articleBodyVo = new ArticleBodyVo();
        articleBodyVo.setContent(articleBody.getContentMarkdown());
        return articleBodyVo;
    }

}
